package com.example.utils;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author ccubee
 * @since 2021/8/26 20:50
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RedisLock {

    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 锁
     *
     * @param key   关键
     * @param value 当前时间加超时时间
     * @return boolean
     */
    public boolean lock(String key, String value) {
        if (Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(key, value))) {
            return true;
        }
        String currentValue = stringRedisTemplate.opsForValue().get(key);
        // 如果锁过期
        if (!StrUtil.isBlank(currentValue) && Long.parseLong(currentValue) < System.currentTimeMillis()) {
            // 获取上一个锁的时间
            String oldValue = stringRedisTemplate.opsForValue().getAndSet(key, value);
            if (!StrUtil.isBlank(oldValue) && oldValue.equals(currentValue)) {
                return true;
            }
        }
        return false;
    }

    public void unLock(String key, String value) {
        try {
            String currentValue = stringRedisTemplate.opsForValue().get(key);
            if (!StrUtil.isBlank(currentValue) && currentValue.equals(value)) {
                stringRedisTemplate.opsForValue().getOperations().delete(key);
            }
        } catch (Exception e) {
            log.error("[redis分布式锁] 解锁异常 {}", e.getMessage());
            e.printStackTrace();
        }

    }

}
